const express = require('express');
const {ApiResponse} = require('../model/response')
const {generateToken, verifyToken} = require('../utils/token')
const userService = require('../service/user')
const loginPhoneService = require('../service/login_phone')
const {log} = require("debug");
const path = require("path");


const router = express.Router();


router.post('/register', async (req, res) => {
    const {phone, password, nickname} = req.body;

    try {
        // 先查询该手机号是否已被注册
        const exist = await userService.countByPhone(phone) > 0;
        if (exist) {
            res.json(ApiResponse.fail().sendMessage("手机号已被注册"));
            return
        }
        // 保存用户到数据库
        const saveUser = await userService.createUser({
            phone, password, nickname
        });
        console.log(saveUser);
        res.json(ApiResponse.ok().sendData({
            userId: saveUser.id
        }))
    } catch (e) {
        console.log(e)
        res.json(ApiResponse.fail())
    }
})


router.get('/code/send', async (req, res) => {
    // 结构获得请求体中的参数
    const {phone} = req.query;
    if (!phone) {
        res.json(ApiResponse.fail().sendMessage("参数为空"))
        return
    }
    try {
        // 生成4位验证码
        const code = Math.floor(Math.random() * 9000 + 1000).toString();
        // 保存验证码到数据库
        await loginPhoneService.createVerifyCode(phone, code)
        // 发送验证码
        res.json(ApiResponse.ok().sendData({code}));
    } catch (e) {
        console.log(e)
        res.json(ApiResponse.fail())
    }
})

router.post('/login/code', async (req, res) => {
    // 结构获得请求体中的参数
    const {phone, code} = req.body;
    if (!phone || !code) {
        res.json(ApiResponse.fail().sendMessage("参数为空"))
        return
    }
    try {
        // 查询验证码
        const loginPhoneRecord = await loginPhoneService.getVerifyCodeByPhone(phone);
        if (!loginPhoneRecord) {
            res.json(ApiResponse.fail().sendMessage("请先获取验证码"))
            return
        }
        // 验证码是否过期（1分钟）
        let {code: verifyCode, createTime} = loginPhoneRecord;
        // 处理时间快8小时问题
        createTime = new Date(createTime).getTime();
        const now = new Date().getTime();
        if (now - createTime > 1000 * 60) {
            res.json(ApiResponse.fail().sendMessage("验证码已过期"))
            return
        }
        // 校验验证码是否填写正确
        if (code !== verifyCode) {
            res.json(ApiResponse.fail().sendMessage("验证码错误"))
            return
        }
        // 查询用户是否存在
        let user = await userService.getByPhone(phone);
        // 如果不存在就注册
        if (!user) {
            user = await userService.createUser({
                phone,
                nickname: "Kaka小跟班_" + phone.slice(7),
                password: "",
                ip: "福建"
            })
        }
        // 签发jwt-token
        const token = generateToken({userId: user.id});
        // 发生响应
        res.json(ApiResponse.ok().sendData({
            token
        }))
    } catch (e) {
        log(e);
        res.json(ApiResponse.fail())
    }
});

router.post('/login/password', async (req, res) => {
    // 结构获得请求体中的参数
    const {phone, password} = req.body;
    if (!phone || !password) {
        res.json(ApiResponse.fail().sendMessage("参数为空"))
        return
    }
    try {
        // 查询用户是否存在
        const user = await userService.getByPhone(phone);
        // 校验密码
        if (user.password !== password) {
            res.json(ApiResponse.fail().sendMessage("密码错误"))
            return
        }
        // 签发jwt-token
        const token = generateToken({userId: user.id});
        // 发生响应
        res.json(ApiResponse.ok().sendData({
            token
        }))
    } catch (e) {
        log(e);
        res.json(ApiResponse.fail())
    }
});

router.get('/info', (req, res) => {
    // 从请求头获取用户id
    const {userId} = req.auth;
    // 从数据库中获取用户信息
    userService
        .getById(userId)
        .then(user => {
            res.json(ApiResponse.ok().sendData({
                id: user.id,
                nickname: user.nickname,
                phone: user.phone,
                ip: user.ip,
                description: user.description,
                avatar: user.avatar,
                backgroundImage: user.backgroundImage,
                createTime: user.createTime,
            }))
        })
        .catch(err => {
            console.log(err)
            res.json(ApiResponse.fail())
        });
});


router.post('/update', (req, res) => {
    // 从请求头获取用户id
    const {userId} = req.auth;
    // 从请求体获取用户信息
    const {nickname, description} = JSON.parse(req.body.json);
    // 组装数据
    const user = {
        id: userId,
        nickname,
        description,
    }
    // 从请求体获取文件
    const now = new Date();
    const timestamp = now.getFullYear() + '_' + now.getTime();

    const {avatar, backgroundImage} = req.files || {};
    // 组装上传文件路径
    if (avatar) {
        avatar.name = userId + `_${timestamp}_avatar_` + avatar.name;
        user.avatar = avatar.name;
        const avatarUploadPath = path.join(__dirname, '../public/upload/', avatar.name);
        // 调用将文件移动到服务器上其他位置的函数
        avatar.mv(avatarUploadPath, (err) => {
            if (err) {
                console.log(err)
                res.json(ApiResponse.fail().sendMessage("上传失败"))
            }
        });
    }
    if (backgroundImage) {
        backgroundImage.name = userId + `_${timestamp}_backgroundImage_` + backgroundImage.name;
        user.backgroundImage = backgroundImage.name;
        const backgroundImageUploadPath = path.join(__dirname, '../public/upload/', backgroundImage.name);
        // 调用将文件移动到服务器上其他位置的函数
        backgroundImage.mv(backgroundImageUploadPath, (err) => {
            if (err) {
                console.log(err)
                res.json(ApiResponse.fail().sendMessage("上传失败"))
            }
        });
    }

    // 更新到数据库中
    userService.updateUser(user)
        .then(() => {
            res.json(ApiResponse.ok().sendMessage("更新成功"))
        })
        .catch(err => {
            console.log(err)
            res.json(ApiResponse.fail())
        });
});


module.exports = router;
